//
//  HDRegistVC.swift
//  HuaDaoPeifu
//
//  Created by ZERO on 2018/6/13.
//  Copyright © 2018年 paiyipai. All rights reserved.
//

import UIKit
import SVProgressHUD

//enum RegistType {
//    case register , resetPwd,resChangePhone
//}


class HDRegistVC: UIViewController {

//    var RegistType:RegistType?
    var progressAlert = HDProgressAlert()
    //passType  0:是从个人中心传进来的，rightBarButton显示“登录”；1:是从登录进来的，rightBarButton不显示“登录”
//    var passType:Int?


    //在登录页点击注册跳到哪里：0表示pop到上一页(个人中心需求)，1表示push到注册页(首页登录需求)
//    var BackToWhere: Int?
    //在注册页点击登陆跳到哪里：0表示pop到上一页(首页需求)，1表示push到登录页(个人中心需求)
//    var logBtnBackToWhere: Int?
    
    // 0登录  1注册
    var ToWhere: Int?
    var accountType: HDUserType?

    
    
    var timer = Timer()
    var timeCount = 60
    
//    init(RegistType: RegistType) {
//        super.init(nibName: nil, bundle: nil)
//        self.RegistType = RegistType
//    }
//    required init?(coder aDecoder: NSCoder) {
//        super.init(coder: aDecoder)
//    }
    var countdownTimer: Timer?
    
    @IBOutlet weak var scrollView: UIScrollView!
    
    @IBOutlet weak var phoneView: UIView!
    @IBOutlet weak var codeView: UIView!
    @IBOutlet weak var passwordView: UIView!
    @IBOutlet weak var passwordView2: UIView!
    
    @IBOutlet weak var identityLabel: UILabel!
    @IBOutlet weak var phoneTF: UITextField!
    @IBOutlet weak var codeTF: UITextField!
    @IBOutlet weak var codeBtn: UIButton!
    
    @IBOutlet weak var pwTF: UITextField!
    @IBOutlet weak var pwTF2: UITextField!
    
    
    @IBOutlet weak var selectIdBtn: UIButton!
    @IBOutlet weak var nextBtn: UIButton!
    
    var isAgree :Int?
    
    override func viewDidLoad() {
        super.viewDidLoad()

        title = "速赔宝（注册）"
        setUI()

        
        // Do any additional setup after loading the view.
    }

    
    func setUI() {
        
        scrollView.contentSize = CGSize(width: 0, height: 603)
        isAgree = 0
        
        phoneView.layer.borderWidth = 1
        phoneView.layer.cornerRadius = 3
        phoneView.layer.borderColor = UIColor(hex: 0xdbdbdb).cgColor
        
        codeView.layer.borderWidth = 1
        codeView.layer.cornerRadius = 3
        codeView.layer.borderColor = UIColor(hex: 0xdbdbdb).cgColor
        
        passwordView.layer.borderWidth = 1
        passwordView.layer.cornerRadius = 3
        passwordView.layer.borderColor = UIColor(hex: 0xdbdbdb).cgColor
        
        passwordView2.layer.borderWidth = 1
        passwordView2.layer.cornerRadius = 3
        passwordView2.layer.borderColor = UIColor(hex: 0xdbdbdb).cgColor
        
        selectIdBtn.layer.cornerRadius = 3
        nextBtn.layer.cornerRadius = 3
        nextBtn.layer.borderWidth = 1
        nextBtn.layer.borderColor = UIColor(red:(255/255.0), green:(138/255.0), blue:(0/255.0), alpha:1.0).cgColor
        
        if accountType == .group{
            self.identityLabel?.text = "团体用户"
            
        }else if accountType == .exclusive  {
            self.identityLabel?.text = "专属用户"
            
        }else if accountType == .personal  {
            self.identityLabel?.text = "个人用户"
            
        }
    }
    
    
    
    func startTimer() {
        codeBtn.isEnabled = false
        timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(beginCountDown), userInfo: nil, repeats: true)
    }
    
    func beginCountDown() {
        // print(timeCount)
        timeCount -= 1
        
        codeBtn.setTitle("(\(timeCount)秒)", for: .disabled)
        if timeCount == 0 {
            codeBtn.isEnabled = true
            timer.invalidate()
            timeCount = 60
        }
        
        
    }
    
    //倒计时
    var remainingSeconds: Int = 0 {
        willSet {
            codeBtn.setTitle("(\(newValue)秒)", for: UIControlState())
            if newValue <= 0 {
                codeBtn.setTitle("重新获取", for: UIControlState())
                isCounting = false
            }
        }
    }
    var isCounting = false {
        willSet {
            if newValue {
                countdownTimer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(updateTime), userInfo: nil, repeats: true)
                remainingSeconds = 60
                codeBtn.setTitleColor(UIColor(hex:0x999999), for: UIControlState())
            } else {
                countdownTimer?.invalidate()
                countdownTimer = nil
                codeBtn.setTitleColor(ConstantColor.appThemeColor, for: UIControlState())
            }
            codeBtn.isEnabled = !newValue
        }
    }
    func updateTime(_ timer: Timer) {
        remainingSeconds -= 1
    }
    
    @IBAction func codeAction(_ sender: UIButton) {
        if phoneTF.text == nil || phoneTF.text == "" {
            progressAlert.pleaseEnterPhoneNumber()
            return
        }
        if phoneTF.text!.characters.count != 11 {
            progressAlert.pleaseEnterRightPhoneNumber()
            return
        }
        
        let reqmode = "1"
//        if self.RegistType == .resChangePhone {
//            reqmode = "3"
//        }
        let authCode = PYPAuthcode(phone: phoneTF.text!, tms: "0", reqmode: reqmode)
        
        HDApiManagerHandler.requestRegAuthcode(authCode) { (result) in
            guard let result = result else{
                return
            }
            
            if result.status == .Success {
                self.startTimer()
                self.isCounting = true
                return
            }
            SVProgressHUD.showError(result.msg)
        }
}
    
    // 密文控制
    @IBAction func canseeAction(_ sender: UIButton) {
        sender.isSelected = !sender.isSelected
        if sender.isSelected {
            sender.setImage(UIImage(named: "yanjing-2"), for: UIControlState.normal)
            pwTF.isSecureTextEntry = false
            var str = ""
            str = pwTF.text!
            pwTF.text = ""
            pwTF.text = str
        }else{
            sender.setImage(UIImage(named: "yanjing-1"), for: UIControlState.normal)
            pwTF.isSecureTextEntry = true
        }
    }
    
    @IBAction func canseeAction2(_ sender: UIButton) {
        sender.isSelected = !sender.isSelected
        if sender.isSelected {
            sender.setImage(UIImage(named: "yanjing-2"), for: UIControlState.normal)
            pwTF2.isSecureTextEntry = false
            var str = ""
            str = pwTF2.text!
            pwTF2.text = ""
            pwTF2.text = str
        }else{
            sender.setImage(UIImage(named: "yanjing-1"), for: UIControlState.normal)
            pwTF2.isSecureTextEntry = true
        }
    }
    
    
    
    // 重选身份
    @IBAction func selectAction(_ sender: UIButton) {
         navigationController?.popViewController(animated: true)
    }
    
    // 下一步
    @IBAction func nextAction(_ sender: UIButton) {
        
        phoneTF.resignFirstResponder()
        codeTF.resignFirstResponder()
        
        if phoneTF.text == nil || phoneTF.text == "" {
            progressAlert.pleaseEnterPhoneNumber()
            return
        }
        if codeTF.text == nil || codeTF.text == "" {
            progressAlert.pleaseEnterAuthCode()
            return
        }
        
        if pwTF.text == nil || pwTF.text == "" {
            progressAlert.enterPassWord()
            return
        }
        if pwTF2.text == nil || pwTF2.text == "" {
            progressAlert.confirmPassWord()
            return
        }
        if pwTF.text != pwTF2.text{
            progressAlert.pleaseEnterEqualPW()
            return
        }
        
        if isAgree != 1 {
           SVProgressHUD.showError("请同意用户协议")
            return

        }
        
        var reqmode:String = "1"
//        if self.RegistType == .resChangePhone {
//            reqmode = "3"
//        }
        
        let ckAuthCode = PYPCkauthcode(phone: phoneTF.text, code:codeTF.text, reqmode:reqmode)
        
        HDApiManagerHandler.requestCKAuthcode(ckAuthCode) { (result) in
            guard let result = result else {
                SVProgressHUD.showError("网络开小差了哦，请稍后再试...")
                return
            }
            if result.status == .Success {
                let select = HDidentityAuthenticationVC()
                select.accountType = self.accountType
                
                var regP = PYPReg()
                regP.phone = self.phoneTF.text!
                regP.code = self.codeTF.text!
                regP.ptxt = self.pwTF.text!.cz_hmacMD5String(withKey: RegistApi.saltStr)
                regP.login_type = String(self.accountType!.rawValue)
                
                select.regStr = regP
                
                self.navigationController?.pushViewController(select, animated: true)
                return
            }
            SVProgressHUD.showError(result.msg)
        }
    }
    
    @IBAction func loginAction(_ sender: UIButton) {
        let loginVC = HDLoginNewVC()
        loginVC.userType = accountType
        navigationController?.pushViewController(loginVC, animated: true)
}
    
    // 同意
    @IBAction func agreeAction(_ sender: UIButton) {
        sender.isSelected = !sender.isSelected
        if sender.isSelected {
            sender.setImage(UIImage(named: "cb_green_on"), for: UIControlState.normal)
            isAgree = 1
        }else{
             sender.setImage(UIImage(named: "cb_green_off"), for: UIControlState.normal)
            isAgree = 0
        }
    }
    
    // 协议
    @IBAction func delegateAction(_ sender: UIButton) {
    navigationController?.pushViewController(HDUserAgreementViewController(), animated: true)

    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
